package com.zw.mes.aspectj;

import com.zw.mes.annotation.LogAnnotation;
import com.zw.mes.entity.sys.Log;
import com.zw.mes.entity.sys.User;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.util.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Description: 日志切面
 *
 * @Author: China.sgl
 * @Date: 2020/7/30 9:42
 */
@Component
@Aspect
@SuppressWarnings("all")
public class LogAspect {

    @Autowired
    private LogService logService;

    @Pointcut("@annotation(com.zw.mes.annotation.LogAnnotation)")
    private void pointCut() { }

    @After("pointCut()")
    public void recordLog(JoinPoint joinPoint) {
        User user = ShiroUtils.getUser();
        if(null!=user){
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
            Log log = new Log();
            log.setAccount(user.getAccount());
            log.setOperator(user.getName());
            log.setTitle(logAnnotation.value());
            log.setOperTime(new Date());
            log.setAddress(ShiroUtils.getIp());
            logService.saveLog(log);
        }
    }
}
